package com.cn.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cn.service.NewsService;

import net.sf.json.JSONArray;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;

/**
 * 接受与发送新闻信息
 * @author ailinfei
 *
 */
public class NewsServlet extends HttpServlet {
	private static final String CONTENT_TYPE = "text/plain; charset=UTF-8";

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		this.ListToJson(req, response);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	/**                                                          
	 * 输出信息
	 * @param response
	 * @param content
	 * @throws IOException                                                                                          
	 */
	private void print(HttpServletResponse response, String content)
			throws IOException {
		response.setContentType(CONTENT_TYPE);
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		PrintWriter write = response.getWriter();
		write.print(content);
		write.close();
	}

	/**                                                          
	 * 新闻信息集合List转换为JSON
	 * @param req
	 * @param response
	 * @throws ServletException
	 * @throws IOException                                                                                          
	 */
	private void ListToJson(HttpServletRequest req, HttpServletResponse response)
			throws ServletException, IOException {
		JSONObject resultJSON = new JSONObject(); 
		JSONArray jsonArray = null;
		String types=req.getParameter("types");
		int pageNum=Integer.parseInt(req.getParameter("page_num"));
		//System.out.println("pageNum:"+pageNum);
		NewsService newsService = new NewsService();
		Date date = new Date(); 
		SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//24小时制  
	    String uptime = sdformat.format(date);  
		try {
			jsonArray = JSONArray.fromObject(newsService.getNews(types,pageNum));
			resultJSON.accumulate("list",jsonArray)
			  .accumulate("uptime", uptime);
			//System.out.println(resultJSON.toString(1,1));
		} catch (JSONException e) {
			e.printStackTrace();
		}
		this.print(response, resultJSON.toString(1, 1));

	}

}
